import {messages} from "share/common";
import React from 'react'
import { DatePicker, message } from 'antd'
import { debounce } from 'lodash-es'

// 判断是否是闰年
const isLeapYear = (year) =>
  (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0

// 判断输入的是否是数字
const isNumber = (keyCode) =>
  (keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 108)

const MONTH2DAY = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] // 每个月的天数

class HlyDatePicker extends DatePicker {
  constructor(props) {
    super(props)
    this.num = 0 // 轮询次数
    this.deboundeError = debounce(message.error, 300)
    this.preSelectionStart = 0
  }

  //处理输入函数
  handleFilter = (e) => {
    const { format = 'YYYY-MM-DD' } = this.props
    const value = this.input.value
    const keyCode = e.keyCode 
    const connectionStr = format.match(/[^a-zA-Z]/)[0] 
    let len = value.length 

    this.preSelectionStart = e.target.selectionStart // 保存当前光标位置

    if (!/^YYYY[-:\/]MM[-:\/]DD$/.test(format)) return // 必须是YYYY-:/MM-:/DD  这三种格式化才走这个逻辑
    if (!value) return 
    if (!isNumber(keyCode)) return 

    let newValue = value

    /************************* 天数处理 ******************************* */
    if (len > 10) {
      this.input.value = this.input.value.slice(0, 10)
      return
    } else if (len === 10) {
      const year = Number(newValue.slice(0, 4))
      const month = Number(newValue.slice(5, 7))
      const day = Number(newValue.slice(8, 10))

      MONTH2DAY[1] = isLeapYear(year) ? 29 : 28 // 闰年29天，平年28天

      if (day < 0 || day > MONTH2DAY[month - 1]) {
        this.deboundeError(messages('common-1.key1301')/*请输入正确日期*/)
        return
      }
    }

    /************************* 月份处理******************************* */
    if (len >= 7) {
      const month = Number(newValue.slice(5, 7))
      if (month > 12) {
        this.deboundeError(messages('common-1.key1302')/*请输入正确月份*/)
        return
      } else {
        if (len === 7) {
          newValue += connectionStr
          len += 1
          this.preSelectionStart = len // len变化之后光标位置也要重新赋值
        }
      }
    } else if (len === 6) {
      let monthOne = Number(newValue.slice(5, 6))
      if (monthOne > 1) {
        newValue = `${newValue.slice(0, 5)}0${monthOne}${connectionStr}`
        len += 2
        this.preSelectionStart = len // len变化之后光标位置也要重新赋值
      }
    }

    /************************* 年份处理******************************* */
    if (len >= 4) {
      if (!/\d{4}/.test(newValue)) {
        this.deboundeError(messages('common-1.key1331')/*请输入正确年份*/)
        return
      }
      if (len === 4) {
        newValue += connectionStr
        len += 1
        this.preSelectionStart = len // len变化之后光标位置也要重新赋值
      }
    }
    this.input.value = newValue
    this.handleCursor(len)
  }

  // 处理光标问题
  handleCursor = (len) => {
    if (len === 10) {
      setTimeout(() => {
        if (this.preSelectionStart === 0 && len === 10)
          this.input.selectionStart = len
      })
    } else {
      setTimeout(() => {
        if (
          this.input.selectionStart !== this.preSelectionStart &&
          this.preSelectionStart === 7
        ) {
          this.input.selectionStart = this.preSelectionStart
        }
      })
    }
  }

  // 日历弹窗出来的事件函数
  handleOpenChange = (open) => {
    let { onOpenChange } = this.props
    onOpenChange && onOpenChange(open)
    if (open) {
      this.getSelectPos()
    } else {
      this.input && this.input.removeEventListener('keyup', this.handleFilter)
    }
  }

  // 轮询获取输入框的dom
  getSelectPos = () => {
    if (this.num < 20) {
      setTimeout(() => {
        const input = document.querySelector('.ant-calendar-input') // 弹窗input的dom
        if (!input) {
          this.getSelectPos()
          this.num++
          return
        } // 如果没有获取到就不处理，也不监听输入事件
        const inputWrapper = input.parentNode.parentNode
        inputWrapper.style.borderBottom = '1px solid #40a9ff'
        this.num = 0
        this.input = input
        if (this.input.value) {
          this.input.selectionStart = this.input.value.length
        }
        input.focus() // 自动获取焦点
        this.input.addEventListener('keyup', this.handleFilter)
      }, 180)
    } else {
      this.num = 0
    }
  }

  render() {
    let props = Object.assign({}, this.props, {
      placeholder: messages('common-1.key1303')/*请输入或选择*/,
      onOpenChange: this.handleOpenChange,
    })
    return (
      <span className='hly-component-date-picker'>
        <DatePicker {...props} />
      </span>
    )
  }
}

export default HlyDatePicker